import {
	baseUrl,
	baseImgUrl
} from '@/api/api.js'
import {
	checkToken,
	getOpenIdBywxCode,
	miniProgramUserLogin,
} from '@/api/common.js'

// 判断是否为json字符串
function isJSONStr(str) {
	if (typeof str === 'string') {
		try {
			var obj = JSON.parse(str);
			if (typeof obj === 'object' && obj) {
				return true;
			} else {
				return false;
			}
		} catch (e) {
			return false;
		}
	}
}
// 上传文件
export const uploadFile = params => {
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('userInfo').token
		uni.uploadFile({
			url: baseUrl + '/sys/common/upload',
			filePath: params,
			name: 'file',
			formData: {
				'biz': 'temp'
			},
			header: {
				'X-Access-Token': token,
			},
			success: res => {
				console.log('文件上传结果', res)
				let act_res = res.data
				if (isJSONStr(act_res)) {
					act_res = JSON.parse(act_res)
				}
				resolve(act_res)
			},
			fail: e => {
				console.log('文件上传失败', e)
				resolve(false)
			}
		});
	});
}


export const getUserLogin = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin', //使用微信登录
			success: function(loginRes) {
				getOpenIdBywxCode({
					code: loginRes.code
				}).then(codeRes => {
					miniProgramUserLogin({
						openId: codeRes.data.openid
					}).then(openRes => {
						if (openRes.data.code == 200) {
							console.log('setsetsetsetsetsetsetsetsetset',openRes.data.result)
							uni.setStorageSync('userInfo', openRes.data.result)
							uni.setTabBarBadge({ //显示数字  
								index: 2, //tabbar下标
								text: '16' //数字
							})
							resolve({
								token_s: openRes.data.result.token,
								status_s: true
							})
						} else {
							resolve({
								status_s: false
							})
						}
					})
				})
			}
		});
	})
}

export const checkTokenNow = () => {
	const userInfo = uni.getStorageSync('userInfo') || {}
	if (userInfo.token) {
		checkToken().then(res => {
			if (!res.data.result) getUserLogin()
		})
	} else {
		getUserLogin()
	}
}